package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <b><code>CategoryServiceImpl</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 24/06/2024 15:35.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@Service("categoryService")
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 菜品分页查询
     * @param page 当前页
     * @param pageSize 每页显示条数
     * @return 查询的分页结果
     */
    @Override
    public R<Page<Category>> queryCategory(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        Page<Category> pageInfo = baseMapper.selectPage(categoryPage, new QueryWrapper<Category>().orderByAsc("sort"));
        return R.success(pageInfo);
    }

    /**
     * 删除分类
     * @param id 分类id
     * @return 是否成功
     */
    @Override
    public R<String> deleteCategoryById(Long id) {
        Integer dishCount = dishMapper.selectCount(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, id));
        Integer setmealCount = setmealMapper.selectCount(new LambdaQueryWrapper<Setmeal>().eq(Setmeal::getCategoryId, id));
        if (!dishCount.equals(0) || !setmealCount.equals(0)) {
            return R.error("已关联菜品或套餐，无法删除");
        }
        this.removeById(id);
        return R.success("删除成功");
    }

}
